package com.heima.seckill.rabbitmq;

import com.heima.seckill.pojo.SeckillOrder;
import com.heima.seckill.pojo.User;
import com.heima.seckill.service.IGoodsService;
import com.heima.seckill.service.IOrderService;
import com.heima.seckill.utils.JsonUtil;
import com.heima.seckill.vo.GoodsVo;
import com.heima.seckill.vo.SeckillMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class MQReceiver {
  @Autowired
  private RedisTemplate redisTemplate;

  @Autowired
  private IGoodsService goodsService;
  @Autowired
  private IOrderService orderService;

  @RabbitListener (queues = "seckillQueue")
  public void receive(String message) {
        log. info("接收的消息: " + message);
        SeckillMessage seckillMessage = JsonUtil.jsonStr2Object (message, SeckillMessage.class);
        String goodId = seckillMessage.getGoodsId();
        User user = seckillMessage. getUser();
        GoodsVo goodsVo = goodsService .findGoodsVoById(goodId);
        if (goodsVo.getStockCount() < 1) {
            return;
        }
        //判断是否重复抢购
        SeckillOrder seckillorder =
                (SeckillOrder) redisTemplate . opsForValue().get("order:"+user.getId()+":" +goodId);
        if (seckillorder != null) {
            return;
        }
        //下单操作
        orderService.seckill(user, goodsVo);
    }

//    @RabbitListener(queues = "queue")
//    public void receive(Object msg){
//        log.info("接收消息 ： "+msg);
//    }
//    @RabbitListener(queues = "queue_fanout01")
//    public void receive01(Object msg){
//        log.info("接收消息 queue_fanout01 ： "+msg);
//    }
//
//    @RabbitListener(queues = "queue_direct01")
//    public void DReceive01(Object msg){
//        log.info("接收消息 direct_direct01 ： "+msg);
//    }
//
//    @RabbitListener(queues = "queue_direct02")
//    public void DReceive02(Object msg){
//        log.info("接收消息 direct_direct02 ： "+msg);
//    }
//    @RabbitListener(queues = "queue_topic01")
//    public void TReceive01(Object msg){
//        log.info("接收消息 queue_topic01 ： "+msg);
//    }
//    @RabbitListener(queues = "queue_topic02")
//    public void TReceive02(Object msg){
//        log.info("接收消息 queue_topic02 ： "+msg);
//    }

}
